package com.docking.heylo.service.impl;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.SysResources;
import com.docking.heylo.dao.entity.SysResourcesExample;
import com.docking.heylo.dao.mapper.SysResourcesMapper;
import com.docking.heylo.enums.EDeleteStatus;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.service.ISysResourceService;
import com.docking.heylo.web.dto.SysResourcesDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service
public class SysResourceServiceImpl implements ISysResourceService {

    @Resource
    private SysResourcesMapper resourcesMapper;


    @Override
    public void saveResource(SysResourcesDto sysResources) {
        SysResourcesExample example = new SysResourcesExample();
        SysResourcesExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(sysResources.getCode());
        if(resourcesMapper.countByExample(example) > 0){
            throw new GeneralException("资源已存在");
        }

        resourcesMapper.insertSelective(new SysResources(){{
            setParentId(sysResources.getParentId());
            setName(sysResources.getName());
            setUrl(sysResources.getUrl());
            setType((byte)sysResources.getType());
            setIcon(sysResources.getIcon());
            setOrderNum(sysResources.getOrderNum());
            setDeleted(EDeleteStatus.notDeleted.getValue().byteValue());
            setCreateAt(new Date());
            setCreateBy(ThreadContext.userId());
            setComponentName(sysResources.getComponentName());
            setCode(sysResources.getCode());
        }});
    }

    @Override
    public PageInfo<Map<String, Object>> resourceList(SysResourcesDto resourcesInput) {
        PageHelper.startPage(resourcesInput.getPageNumber(), resourcesInput.getSize());
        return new PageInfo<>(resourcesMapper.resourceList());
    }

    @Override
    public SysResources selectById(Integer id) {
        return resourcesMapper.selectByPrimaryKey(id);
    }

    @Override
    public void editResource(SysResourcesDto resources) {
        resourcesMapper.updateByPrimaryKeySelective(new SysResources(){{
            setId(resources.getId());
            setParentId(resources.getParentId());
            setName(resources.getName());
            setUrl(resources.getUrl());
            setType((byte)resources.getType());
            setIcon(resources.getIcon());
            setOrderNum(resources.getOrderNum());
            setUpdateAt(new Date());
            setUpdateBy(ThreadContext.userId());
            setComponentName(resources.getComponentName());
            setCode(resources.getCode());
        }});
    }

    @Override
    public void delResource(Integer id) {
        resourcesMapper.deleteByPrimaryKey(id);
    }




}
